package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.dialog.BuyGoodsDialogFragment;
import com.meixiang.fragment.shopping.GoodsDetailInfoFragment;
import com.meixiang.fragment.shopping.GoodsImageTextViewPagerFragment;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.view.TitleView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品详情页
 *
 * @author LZRUI
 */
public class GoodsDetailActivity extends BaseActivity implements BuyGoodsDialogFragment.CacheListener, GoodsDetailInfoFragment.FavoriteListener {

    public static final String TAG = "GoodsDetailActivity";
    public static String GOODS_ID = "goods_id";

    @Bind(R.id.iv_collect)
    TextView ivCollect; // 收藏的图标
    @Bind(R.id.tv_collect)
    TextView tvCollect; // 收藏文本
    @Bind(R.id.title)
    TitleView titleView; // 标题栏

    private boolean mIsCollect = false; // 当前收藏的状态

    private String goodsId;
    private String style;
    private HashMap<Integer, Set<Integer>> lastSelectedMap = new HashMap<>(); // 传给BuyGoodsDialogFragment中Adapter的缓存规格列表
    private int buyGoodsNum = 1;
    private boolean isHeadQuarter; // 是否是总店

    private FragmentManager fragmentManager;
    private GoodsImageTextViewPagerFragment goodsImageTextViewPagerFragment;
    private GoodsDetailInfoFragment goodsDetailInfoFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_goods_detail);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            goodsId = getIntent().getStringExtra(GOODS_ID);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    protected void initTitle() {
        titleView.setTitle("商品详情");
        titleView.setLeftImageButton(R.mipmap.back);
        titleView.showLeftButton(this);
        titleView.setRightImageButton(R.mipmap.shopping_car);
        titleView.showRightButton(this);
    }

    @Override
    protected void initView() {
        fragmentManager = getSupportFragmentManager();
        goodsDetailInfoFragment = (GoodsDetailInfoFragment) fragmentManager.findFragmentById(R.id.fl_first_pager);
        if (goodsDetailInfoFragment == null) {
            goodsDetailInfoFragment = GoodsDetailInfoFragment.newInstance(goodsId);
            fragmentManager.beginTransaction().add(R.id.fl_first_pager, goodsDetailInfoFragment).commit();
        }
        goodsImageTextViewPagerFragment = (GoodsImageTextViewPagerFragment) fragmentManager.findFragmentById(R.id.fl_second_pager);
        if (goodsImageTextViewPagerFragment == null) {
            goodsImageTextViewPagerFragment = new GoodsImageTextViewPagerFragment().newInstance(goodsId);
            fragmentManager.beginTransaction().add(R.id.fl_second_pager, goodsImageTextViewPagerFragment).commit();
        }
        goodsDetailInfoFragment.setFavoriteListener(this);
    }

    @Override
    protected void setData() {

    }

    @Override
    @OnClick({R.id.ll_collect, R.id.tv_add_shopping_car, R.id.tv_buy, R.id.ll_call})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            // 返回按钮
            case R.id.title_left:
                finish();
                break;
            // 购物车按钮
            case R.id.title_right:
                startActivity(new Intent(this, ShoppingCartActivity.class));
                break;
            // 收藏
            case R.id.ll_collect:
                favorite(mIsCollect);
                break;
            // 添加购物车
            case R.id.tv_add_shopping_car:

                BuyGoodsDialogFragment.newInStance(true, goodsId, lastSelectedMap, buyGoodsNum).setCacheListener(this).show(getSupportFragmentManager(), BuyGoodsDialogFragment.TAG);
                break;
            // 立即购买
            case R.id.tv_buy:
                BuyGoodsDialogFragment.newInStance(false, goodsId, lastSelectedMap, buyGoodsNum).setCacheListener(this).show(getSupportFragmentManager(), BuyGoodsDialogFragment.TAG);
                break;
            // 客服
            case R.id.ll_call:
                // TODO 进入客服聊天页面
                if (MXApplication.mApp.getUser() != null) {
                    if (isHeadQuarter) {
                        Tool.SelectCustomerService(context, true);
                    } else {
                        Tool.SelectCustomerService(context, false);
                    }
                }
                break;
        }
    }

    /**
     * 是否是总店
     *
     * @param code
     */
    public void setIsHeadQuarter(String code) {
        //1 是总店 0不是总店
        isHeadQuarter = code.equals("1");
    }

    /**
     * 判断是否收藏成功
     *
     * @param isCollect true：收藏，false：取消收藏
     */
    public void checkCollect(boolean isCollect, boolean isFirst) {
        mIsCollect = isCollect;
        if (isCollect) {
            // 收藏成功
            if (!isFirst) {
                Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show();
            }
            tvCollect.setText("已收藏");
            ivCollect.setEnabled(true);
        } else {
            if (!isFirst) {
                Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
            }
            tvCollect.setText("收藏");
            ivCollect.setEnabled(false);
        }
    }

    /**
     * 收藏
     */
    private void favorite(boolean isCollect) {
        HttpParams params = new HttpParams();
        params.put("goodsId", goodsId);
        if (isCollect) {
            // 已收藏，则取消收藏
            params.put("opera", "2");
        } else {
            params.put("opera", "1");
        }

        HttpUtils.post(Config.GOODS_FAVORITE, TAG, params, new HttpCallBack(GoodsDetailActivity.this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                checkCollect(!mIsCollect, false);
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(GoodsDetailActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void cacheSelected(HashMap<Integer, Set<Integer>> map) {
        if (lastSelectedMap == null) return;
        lastSelectedMap = map; // 缓存选中的标签
    }

    @Override
    public void cacheBuyGoodsNum(int num) {
        buyGoodsNum = num; // 缓存购买数量
    }
}
